
/*
上传又拍云
 */
import 'dart:io';
import 'dart:typed_data';

import 'package:reabampos/src/reabam/operation/rb_api.dart';
import 'package:reabampos/src/reabam/ui/demo/pagestate_test_android.dart';
import 'package:reabampos/src/reabam/ui/pagestate_main_webview.dart';
import 'package:reabampos/src/reabam/ui/support/support_get_good_items.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';
import 'package:image_picker/image_picker.dart';

class SupportHandlePhoto {

  MainWebViewStatePage statePage;
  late String imageRecognitionDirectoryPath;

  SupportHandlePhoto(this.statePage){
    imageRecognitionDirectoryPath='${XTempData.appDocumentsDirectoryPath}/productRecognitionImages';
    XFileUtils.initFolderPath(imageRecognitionDirectoryPath);
  }

  /////////////////////////////////////////////////////

  bool isUploading=false;
  void selectAndUploadPhoto(dynamic data){
    if(isUploading){
      statePage.toast('正在上传图片中');
      return;
    }

    if('camera'==data){

      XFlutterUtils.openImagePicker(
          isCamera: true,
          onCallbackResult: (XFile? file){
            if(file!=null){
              XLogUtils.printLog('---file.path=${file.path}');
              uploadYoupaiuyn(file.path??'');
            }
          });

    }else if('selectPhoto'==data){

      XFlutterUtils.openImagePicker(
          isCamera: false,
          onCallbackResult: (XFile? file){
            if(file!=null){
              XLogUtils.printLog('---file.path=${file.path}');
              uploadYoupaiuyn(file.path??'');
            }
          });
    }

  }


  //上传又拍云
  String? imageZone;
  //
  void uploadYoupaiuyn(String filePath){
    isUploading=true;
    statePage.showLoading();
    //1.
    RBBaseApi.getYoupaiyunConfig(
        succeed: (dynamic response, Map<String, dynamic> responseMap, Map<String, dynamic> headers_response) {
          imageZone=responseMap['imageZone'];
          String url=responseMap['action']??'';
          String policy=responseMap['policy']??'';
          String signature=responseMap['signature']??'';
          //2.
          XYoupaiyunUtils.uploadFile(
            url: url,
            filePath: filePath,
            policy: policy,
            signature: signature,
            succeed: (String result, Map<String, dynamic> headers_response) {

              Map<String,dynamic> map=XJsonUtils.json2Map(result);

              String fileFullUrl='$imageZone${map['url']}';
              map['fileFullUrl']=fileFullUrl;
              //map['filePath'] = filePath;
              //{"image-type":"JPEG","image-frames":1,"image-height":3280,"sign":"26751e9d6ede7b6e10d7197d124c2da0","code":200,"file_size":2493908,"image-width":2464,"url":"/other/20240426013113_djgtwot9fif67gq4.jpg","time":1714095074,"message":"ok","mimetype":"image/jpeg","fileFullUrl":"https://upaiyun.reabam.com/other/20240426013113_djgtwot9fif67gq4.jpg"}
              //XLogUtils.printLog('---map=${XJsonUtils.obj2Json(map)}');
              //3.
              RBBaseApi.saveUpYunInfo(
                  file_youpaiyun: map,
                  succeed: (response, Map<String, dynamic> responseMap, Map<String, dynamic> headers_response) {
                    statePage.hideLoading();
                    isUploading=false;
                    String attachmentId = responseMap['DataLine'][0];
                    map['attachmentId']=attachmentId;

                    XLogUtils.printLog('---map=${XJsonUtils.obj2Json(map)}');
                    statePage.runJSFunction(statePage.jsFunction_getAppValue('selectAndUploadPhoto',XJsonUtils.obj2Json(map)));

                  },
                  failed: (String code, String msg) {
                    statePage.hideLoading();
                    isUploading=false;
                    statePage.toast(msg);
                  }
              );

            },
            failed: (String code, String msg) {
              statePage.hideLoading();
              isUploading=false;
              statePage.toast(msg);
            },
          );


        },
        failed: (String code, String msg) {
          statePage.hideLoading();
          isUploading=false;
          statePage.toast(msg);
        }

    );

  }

  //识别图片商品
  void aiRecognitionImage(){

    XFlutterUtils.openImagePicker(
        isCamera:true,
        onCallbackResult: (file) async {
          String? path=file?.path;
          XLogUtils.printLog('---原图片地址=$path');
          if(!XStringUtils.isEmpty(path)){

            String? newFilePath= await XImageUtils.compressFileImageToNewFilePath(
                minWidth:1600,
                minHeight:1200,
                quality: 50,
                filePath: path!,
                targetPath: '$imageRecognitionDirectoryPath/${XDateUtils.getCurrentTime_ms()}.jpeg'
            );

            XLogUtils.printLog('---新图片地址=$newFilePath');

            File newFile=File(newFilePath??'');
            if(newFile.existsSync()){
              Uint8List dU8=await newFile.readAsBytes();
              String base64Str=XJiamiUtils.uint8ListToBase64(dU8);

              statePage.showLoading();
              RBBaseApi.aiRecognitionImage(
                  file: base64Str,
                  succeed: (response, Map<String, dynamic> responseMap, Map<String, dynamic> headers_response) {
                    statePage.hideLoading();

                    XImageUtils.getImageInfo(imageBytes:dU8, callback: (Map<String,dynamic>? res){
                      XLogUtils.printLog('---新图片width=${res?['width']},height=${res?['height']}');

                      responseMap['base64String']=base64Str;
                      responseMap['imgWH']=res;
                      SupportGetGoodItems.getAiRecognitionItemSimpleJson(responseMap,(dynamic json){

                        XLogUtils.printLog('---getAiRecognitionItemSimpleJson =$json');
                        //判断字符串长度
                        int jsonLength=json.length;

                        //分割字符串长度算法
                        int cutLength=1000000;
                        //分割总数
                        int totalLines=0;
                        if(jsonLength>(cutLength+1)){
                          //需要分割
                          XLogUtils.printLog('---需要分割');

                          int cutNum= (jsonLength/cutLength).truncate();
                          totalLines=cutNum;

                          //
                          if(jsonLength%cutLength!=0){
                            totalLines=cutNum+1;
                          }
                          //cutNum=2
                          for(int i=0;i<cutNum;i++){
                            String key1='$i';
                            String json1=json.substring(i*cutLength,(i+1)*cutLength);
                            statePage.runJSFunction(statePage.jsFunction_offlineGoodItems_longJson('aiRecognitionImageCut2',json1,key1,'$totalLines'));
                          }

                          //
                          if(jsonLength%cutLength!=0){
                            String key1='$cutNum';
                            String json1=json.substring(cutNum*cutLength);
                            statePage.runJSFunction(statePage.jsFunction_offlineGoodItems_longJson('aiRecognitionImageCut2',json1,key1,'$totalLines'));
                          }

                        }else{
                          //不需要分割
                          XLogUtils.printLog('---不需要分割');
                          statePage.runJSFunction(statePage.jsFunction_getAppValue('aiRecognitionImage',json));
                        }

                      });

                    });

                  },
                  failed: (String code, String msg) {
                    statePage.hideLoading();
                    statePage.toast(msg);
                  }
              );

            }

          }
        });
  }


}